package com.example.abe.diandi.util;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;

import com.example.abe.diandi.R;
import com.example.abe.diandi.common.BitmapCompressWaitDialog;
import com.example.abe.diandi.main.MyApplication;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import example.abe.com.framework.util.FileUtil;
import example.abe.com.framework.util.ToastUtil;

/**
 * Created by abe on 17/8/26.
 * 获取照片工具类
 */
public class TakePhotoUtil {
    /**
     * 请求码
     */
    public final static int ALBUM_REQUEST_CODE = 1001;
    public final static int CAMERA_REQUEST_CODE = 1002;
    /**
     * 获取照片的类型
     */
    public final static int ALBUM_TYPE = 1;
    public final static int TAKE_PHOTO_TYPE = 2;

    // 拍照路径
    private String mCameraPath;
    // 主线程Handler
    private Handler mHandler;
    // 图片压缩中
    private BitmapCompressWaitDialog mDialog;
    // 上下文
    private Context mContext;

    public TakePhotoUtil(Context context){
        mContext = context;
        mHandler = new Handler(Looper.getMainLooper());
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mDialog = new BitmapCompressWaitDialog(mContext);
            }
        });
    }

    /**
     * 拍照方法
     */
    public void takePhoto(Fragment fragment) {
        //验证activity
        if (NullUtil.isNullFragment(fragment)) {
            throw new IllegalArgumentException("Fragment为空或者格式不对!");
        }
        // 指定相机拍摄照片保存地址
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File cameraFile = FileUtil.getImageFile(System.currentTimeMillis() + ".jpg");
            mCameraPath = cameraFile.getAbsolutePath();
            Intent intent = new Intent();
            // 指定开启系统相机的Action
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
            // 把文件地址转换成Uri格式
            Uri uri = Uri.fromFile(cameraFile);
            // 设置系统相机拍摄照片完成后图片文件的存放地址
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            fragment.startActivityForResult(intent, CAMERA_REQUEST_CODE);
        } else {
            ToastUtil.makeTextLong(R.string.please_check_sd_card);
        }
    }

    /**
     * 打开相册
     */
    public void openAlbum(Fragment fragment) {
        //验证activity
        if (NullUtil.isNullFragment(fragment)) {
            throw new IllegalArgumentException("Fragment为空或者格式不对!");
        }
        //从相册中获取图片
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        fragment.startActivityForResult(intent, ALBUM_REQUEST_CODE);
    }

    /**
     * 获取照片回调
     * @param requestCode 请求码
     * @param resultCode  结果码
     * @param data        数据
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data,
                                 OnTakePhotoListener listener){
        if (listener == null){
            return;
        }
        String path = onTakePhotoActivityResult(requestCode, resultCode);
        if (!NullUtil.isEmptyString(path)){
            takePhotoFinish(TAKE_PHOTO_TYPE, path, listener);
            return;
        }
        path = onOpenAlbumActivityResult(requestCode, resultCode, data);
        if (!NullUtil.isEmptyString(path)){
            takePhotoFinish(ALBUM_TYPE, path, listener);
            return;
        }
    }

    /**
     * 获取照片完成
     * @param type 获取照片途径（ALBUM_TYPE TAKE_PHOTO_TYPE）
     * @param path 照片全路径
     * @param listener 拍照成功监听
     */
    private void takePhotoFinish(final int type, final String path,
                                 final OnTakePhotoListener listener){
        //显示压缩中dialog
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mDialog.show();
            }
        });
        //开始压缩
        new Thread(new Runnable() {
            @Override
            public void run() {
                //压缩照片，最大500KB
                compressPhoto(path, 4000, 4000, 500);
                //结束压缩中dialog
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mDialog.dismiss();
                    }
                });
                //拍照成功监听
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        listener.onTakePhotoFinish(type, path);
                    }
                });
            }
        }).start();

    }

    /**
     * 拍照回调
     *
     * @param requestCode 请求码
     * @param resultCode  结果码
     */
    private String onTakePhotoActivityResult(int requestCode, int resultCode) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == CAMERA_REQUEST_CODE) {
                if (!NullUtil.isEmptyString(mCameraPath)){
                    return mCameraPath;
                }
            }
        }
        return null;
    }

    /**
     * 相册回调
     *
     * @param requestCode 请求码
     * @param resultCode  结果码
     * @param data        数据
     */
    private String onOpenAlbumActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == ALBUM_REQUEST_CODE) {
                try {
                    Uri uri = data.getData();
                    final String absolutePath = getAbsolutePath(uri);
                    if (!NullUtil.isEmptyString(absolutePath)){
                        return absolutePath;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 解析图片全路径
     * @param uri 图片URI
     * @return 图片全路径
     */
    private String getAbsolutePath(Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = MyApplication.getInstance().getContentResolver()
                    .query(uri, new String[]{MediaStore.Images.ImageColumns.DATA},
                            null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(
                            MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    /**
     * 压缩照片
     * @param path 照片路径
     * @param maxSize 照片最大大小
     */
    private void compressPhoto(String path,int targetWidth, int targetHeight, int maxSize){
        File file = new File(path);
        //图片不存在
        if (!file.exists()){
            ToastUtil.makeText("图片不存在");
            return;
        }
        //获取图片
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        // 部分手机会对图片做旋转，这里检测旋转角度
        bitmap = ImageUtil.rotateBitmapByExif(path, bitmap);
        //压缩图片
        bitmap = ImageUtil.compressBySize(bitmap, targetWidth, targetHeight);
        byte[] bytes = ImageUtil.compress2ByteArrayByQuality(bitmap, maxSize);
        ImageUtil.recycleBitmap(bitmap);
        //重现载入压缩后的图片
        if (file.exists()){
            file.delete();
        }
        try {
            file.createNewFile();
            OutputStream out = new FileOutputStream(file);
            out.write(bytes);
            out.flush();
            out.close();
            bytes = null;
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public interface OnTakePhotoListener{
        void onTakePhotoFinish(int type, String path);
    }
}
